<template>
  <el-row type="flex" justify="center">
    <el-col :span="8" class="app">
      <el-container>
        <el-header>
          <!-- 绑定事件监听addTask -->
          <!--<Header @addTask="addTask"/> -->
          <Header ref="header"/>
        </el-header>
        <el-main>
          <!-- 消息订阅及发布 导入类库命令：npm install --save pubsub-js -->
          <List :todos="todos"/>
        </el-main>
        <el-footer>
          <!--<Footer :todos="todos" :selectAll="selectAll" :deleAll="deleAll"/>-->
          <!-- 组件间通信 slot -->
          <Footer>
            <el-checkbox v-model="selectStatus" slot="checkAll">已经完成{{selectedSize}} / 全部{{todos.length}}</el-checkbox>
            <el-button size="mini" type="danger" @click="deleAll" :disabled="selectedSize===0" slot="deleAll">清除已完成任务</el-button>
          </Footer>
        </el-footer>
      </el-container>
    </el-col>
  </el-row>
</template>

<script>
import Pubsub from 'pubsub-js'
import Header from './commponents/Header'
import List from './commponents/List'
import Footer from './commponents/Footer'
import storageUtils from './utils/storageUtils'

export default {
  mounted () {
    this.$refs.header.$on('addTask', this.addTask)

    // 订阅消息
    Pubsub.subscribe('deleTask', (msg, index) => {
      console.log('订阅消息deleTask')
      this.deleTask(index)
    })
  },
  data () {
    return {
      // 从localStorage中读取todos
      // todos: JSON.parse(window.localStorage.getItem('todos_key') || '[]')
      todos: storageUtils.getTodos()
    }
  },
  computed: {
    selectStatus: {
      get () {
        return this.selectedSize === this.todos.length && this.selectedSize > 0
      },
      set (status) {
        this.selectAll(status)
      }
    },
    selectedSize () {
      return this.todos.reduce((preTatal, todo) => preTatal + (todo.status ? 1 : 0), 0)
    }
  },
  watch: { // 监视
    todos: {
      deep: true, // 深度监视
      /* handler: function (value) {
        // 将最新的todos保存到localStorage中
        console.log(JSON.stringify(value))
        // window.localStorage.setItem('todos_key', JSON.stringify(value))
        storageUtils.saveTodos(value)
      } */
      handler: storageUtils.saveTodos
    }
  },
  methods: {
    addTask (content) {
      this.todos.unshift({status: false, content: content})
    },
    deleTask (index) {
      this.todos.splice(index, 1)
    },
    selectAll (status) {
      this.todos.forEach(todo => {
        todo.status = status
      })
    },
    deleAll (list) {
      // 过滤
      this.todos = this.todos.filter(todo => !todo.status)
    }
  },
  components: {
    Header,
    List,
    Footer
  }
}
</script>

<style>
  *{padding: 0; margin: 0;}
  .app{
    border-style:solid;
    border-color:#CCCCCC;
    border-width: 1px;
    border-radius: 3px;
    padding: 10px;
  }
  .el-header{
    padding: 0px;
  }
  .el-main{
    padding: 0px;
  }
  .el-footer{
    padding: 0px;
  }
</style>
